<template>
  <div style="position: relative; width: 100%; height: 100%; padding: 0">
    <div class="page-content" v-if="!showDetail && !showPatientInfo">
      <a-card style="width: 100%; height: 100%">
        <div class="header">
          <Condition
            :condition="condition"
            :btns="['search', 'reset']"
            @search="searchHandle"
            @reset="reset"
          />
          <div style="display: flex; align-items: center; justify-content: space-between">
            <a-radio-group
              button-style="solid"
              v-model:value="raidoValue"
              @change="raidoValueChange"
            >
              <a-radio-button value="todo">
                待办({{ dispatchAllCounts ? dispatchAllCounts.noSend : 0 }})
              </a-radio-button>
              <a-radio-button value="done">
                已推送({{ dispatchAllCounts ? dispatchAllCounts.send : 0 }})
              </a-radio-button>
            </a-radio-group>
            <div>
              <a-button v-if="raidoValue == 'todo'" type="primary" @click="batchPush"
                >批量推送方案</a-button
              >
            </div>
          </div>
          <!-- <span> 共筛选出 {{ pagination.total }} 条数据 </span> -->
        </div>
        <div class="main">
          <a-table
            class="table"
            size="small"
            :loading="loading"
            :dataSource="List"
            :columns="columns"
            :pagination="pagination"
            @change="paginationChange"
            :sticky="{ offsetHeader: 0 }"
            :row-selection="rowSelection"
            :row-key="'id'"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex == 'no'">
                {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
              </template>
              <template v-else-if="column.dataIndex === 'patName'">
                <span class="patName" @click="toDetail(record)" type="link">
                  {{ record.patName }} {{ record.gender }} {{ record.age }}
                </span>
                <!-- <a-button @click="toDetail(record)" type="link">{{ record.patName }}</a-button> -->
              </template>
              <template v-else-if="column.dataIndex === 'managerName'">
                <a-button type="link" :disabled="!record.questionState" @click="followInfo(record)">
                  减重问卷
                </a-button>
              </template>
              <template v-else-if="column.dataIndex === 'memberState'">
                <a-tag
                  v-if="record.memberState == '生效中'"
                  style="color: #00b42a; background-color: #e8f7ff; border: 1px solid #00b42a"
                >
                  生效中
                </a-tag>
                <a-tag
                  v-if="record.memberState == '已中止'"
                  style="color: #1d2129; background-color: #f2f3f5; border: 1px solid #1d2129"
                >
                  已中止
                </a-tag>
                <a-tag
                  v-if="record.memberState == '已过期'"
                  style="color: #1d2129; background-color: #f2f3f5; border: 1px solid #1d2129"
                >
                  已过期
                </a-tag>
              </template>
              <template v-else-if="column.dataIndex === 'buyTime'">
                <template v-if="record.buyTime">
                  <span>{{ dayjs(record.buyTime).format('YYYY-MM-DD HH:mm') }}</span>
                  ~
                  <span v-if="record.expiredTime">{{
                    dayjs(record.expiredTime).format('YYYY-MM-DD HH:mm')
                  }}</span>
                </template>
              </template>
              <template v-else-if="column.dataIndex === 'questionState'">
                <span style="color: #00b42a" v-if="record.questionState">
                  <CheckCircleFilled two-tone-color="#00B42A" />
                  已填写
                </span>
                <span style="color: #f53f3f" v-if="!record.questionState">
                  <ExclamationCircleFilled two-tone-color="#F53F3F" />
                  未填写
                </span>
              </template>
              <template v-else-if="column.dataIndex === 'aiState'">
                <span style="color: #3491fa" v-if="record.aiState == '生成中'">
                  <ExclamationCircleFilled />
                  生成中
                </span>
                <span style="color: #f53f3f" v-else-if="record.aiState == '生成失败'">
                  <CloseCircleOutlined />
                  生成失败
                </span>
                <span style="color: #00b42a" v-else-if="record.aiState == '已生成'">
                  <CheckCircleFilled />
                  已生成
                </span>
                <span v-else>/</span>
              </template>
              <template v-else-if="column.dataIndex === 'pathName'">
                {{ record.pathName ? record.pathName : '/' }}
              </template>
              <template v-else-if="column.dataIndex === 'serviceState'">
                <span style="color: #ff7d00" v-if="record.serviceState == 'TODO'">
                  <ExclamationCircleFilled two-tone-color="#FF7D00" />
                  待执行
                </span>
                <span style="color: #3491fa" v-if="record.serviceState == 'DOING'">
                  <ExclamationCircleFilled two-tone-color="#3491FA" />
                  处理中
                </span>
                <span style="color: #3491fa" v-if="record.serviceState == 'REPROCESSING'">
                  <ExclamationCircleFilled two-tone-color="#3491FA" />
                  处理中
                </span>
                <span style="color: #0fc6c2" v-if="record.serviceState == 'DONE'">
                  <CheckCircleFilled two-tone-color="#0FC6C2" />
                  已推送
                </span>
                <span style="color: #1d2129" v-else-if="record.serviceState == 'EXPIRED'">
                  <CloseCircleOutlined two-tone-color="#1d2129" />
                  已过期
                </span>
              </template>
              <template v-else-if="column.dataIndex === 'action'">
                <a-button
                  v-if="raidoValue === 'todo'"
                  type="link"
                  @click="addOrUpdateHandle(record)"
                  :disabled="record.memberState != '生效中'"
                >
                  操作
                </a-button>
                <a-button
                  v-else
                  type="link"
                  @click="addOrUpdateHandle(record)"
                  :disabled="record.memberState != '生效中'"
                  >修改</a-button
                >
              </template>
            </template>
          </a-table>
        </div>
      </a-card>
      <FollowInfo ref="followInfoRef" />
    </div>
    <ManaPlan ref="manaPlanRef" v-if="showDetail" @close="goBack" />
    <PatientInfo ref="patientInfoRef" v-if="showPatientInfo" @close="gopatientBack" />

    <!-- 推送方案确认框 -->
    <a-modal
      v-model:open="isPushPlan"
      title=""
      :closable="false"
      :footer="null"
      :maskClosable="false"
    >
      <a-spin :spinning="isCreateHealthInfo">
        <div style="padding-top: 16px">
          <a-empty :image-style="{ height: '110px' }">
            <template #image>
              <div>
                <img
                  style="width: 162px; height: 110px"
                  src="@/assets/health/plan-image.png"
                  alt=""
                />
              </div>
            </template>
            <template #description>
              <div style="margin: 24px 0; font-size: 16px; color: #1d2129; text-align: left">
                点击确认向已勾选的患者批量推送方案，健康任务将在明天开始正式提醒，确定向患者推送方案吗？
              </div>
              <div>
                <a-space>
                  <a-button @click="isPushPlan = false">暂不推送</a-button>
                  <a-button type="primary" @click="pushPlanBtn">推送方案</a-button>
                </a-space>
              </div>
            </template>
          </a-empty>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import Condition from '@/components/ConditionSearch/index.vue'
import {
  CheckCircleFilled,
  ExclamationCircleFilled,
  CloseCircleOutlined
} from '@ant-design/icons-vue'
import { ref, onMounted, reactive, unref } from 'vue'
import ManaPlan from '@/views/healthManaWorkbench/implement/manaPlan.vue'
import { getDispatchList, batchPushScheme, questionAnswer } from '@/api/healthManaWorkbench/index'
import PatientInfo from '@/views/examinatePatients/patientInfo.vue'
import dayjs from 'dayjs'
import { useRoute, useRouter } from 'vue-router'
import store from '@/store'
import FollowInfo from '../dispatch/followInfo.vue'
import { message } from 'ant-design-vue'

const route = useRoute()
const router = useRouter()
const loading = ref<boolean>(false)
const List = ref<any[]>([])
const showDetail = ref(false)
const showPatientInfo = ref(false)
const raidoValue = ref('todo')

type Key = string | number
const selectedKeys = ref<Key[]>([])
const isPushPlan = ref(false)
const isCreateHealthInfo = ref(false)

const dispatchAllCounts = ref()
const condition: any = ref([])
const conditioning = ref<any[]>([
  {
    title: '服务包购买时间',
    dataIndex: 'buyTime',
    type: 'dayRange',
    value: [],
    format: 'YYYY-MM-DD HH:mm',
    showTime: true,
    style: { width: '300px' }
  },
  {
    title: '',
    dataIndex: 'condition',
    type: 'input',
    value: '',
    placeholder: '请输入姓名/证件号'
  },
  //   {
  //     title: '服务包222',
  //     dataIndex: 'questionState',
  //     type: 'select',
  //     value: undefined,
  //     data: [
  //       {
  //         label: '未填写111',
  //         value: false
  //       },
  //       {
  //         label: '已填写22',
  //         value: true
  //       }
  //     ],
  //     placeholder: '请选择服务包'
  //   },
  {
    title: '服务状态',
    dataIndex: 'serviceState',
    type: 'select',
    value: undefined,
    data: [
      {
        label: '待执行',
        value: 'TODO'
      },
      {
        label: '处理中',
        value: 'DOING'
      }
    ],
    placeholder: '请选择服务状态'
  },
  {
    title: '会员状态',
    dataIndex: 'memberState',
    type: 'select',
    value: undefined,
    placeholder: '请选择会员状态',
    data: [
      {
        label: '生效中',
        value: 1
      },
      {
        label: '已过期',
        value: 8
      }
    ]
  }
])

const conditionEd = ref<any[]>([
  {
    title: '服务包购买时间',
    dataIndex: 'buyTime',
    type: 'dayRange',
    value: [],
    format: 'YYYY-MM-DD HH:mm',
    showTime: true,
    style: { width: '300px' }
  },
  //   {
  //     title: '报告生成时间',
  //     dataIndex: 'visitTime',
  //     type: 'dayRange',
  //     value: [],
  //     format: 'YYYY-MM-DD HH:mm',
  //     showTime: true,
  //     style: { width: '300px' }
  //   },
  {
    title: '',
    dataIndex: 'condition',
    type: 'input',
    value: '',
    placeholder: '请输入姓名/证件号'
  },
  {
    title: '会员状态',
    dataIndex: 'memberState',
    type: 'select',
    value: undefined,
    placeholder: '请选择会员状态',
    data: [
      {
        label: '生效中',
        value: 1
      },
      {
        label: '已过期',
        value: 8
      }
    ]
  }
  //   {
  //     title: '',
  //     dataIndex: 'questionState',
  //     type: 'select',
  //     value: undefined,
  //     data: [
  //       {
  //         label: '未填写',
  //         value: false
  //       },
  //       {
  //         label: '已填写',
  //         value: true
  //       }
  //     ],
  //     placeholder: '请选择问卷状态'
  //   }
])
const columns = ref<any[]>([])
const columnsData = ref<any>({
  todo: [
    {
      title: '序号',
      dataIndex: 'no',
      key: 'no',
      align: 'left',
      width: 80
    },
    {
      title: '账号',
      dataIndex: 'userPhone',
      key: 'userPhone',
      align: 'left'
    },
    {
      title: '就诊人手机号',
      dataIndex: 'phone',
      key: 'phone',
      align: 'left'
    },
    {
      title: '就诊人',
      dataIndex: 'patName',
      key: 'patName',
      align: 'left'
    },
    {
      title: '证件号',
      dataIndex: 'idNo',
      key: 'idNo',
      align: 'left',
      width: 150
    },
    {
      title: '会员状态',
      dataIndex: 'memberState',
      key: 'memberState',
      align: 'left'
    },
    {
      title: '服务包有效期',
      dataIndex: 'buyTime',
      key: 'buyTime',
      align: 'left',
      width: 150
    },
    {
      title: '服务包名称',
      dataIndex: 'tradeName',
      key: 'tradeName',
      align: 'left'
    },
    {
      title: '管理路径',
      dataIndex: 'pathName',
      key: 'pathName',
      align: 'left'
    },
    {
      title: '问卷',
      dataIndex: 'managerName',
      key: 'managerName',
      align: 'left',
      width: 100
    },
    {
      title: '服务团队',
      dataIndex: 'groupName',
      key: 'groupName',
      align: 'left'
    },
    {
      title: 'AI状态',
      dataIndex: 'aiState',
      key: 'aiState',
      align: 'left'
    },
    {
      title: '服务状态',
      dataIndex: 'serviceState',
      key: 'serviceState',
      align: 'left'
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      align: 'left',
      width: 100
    }
  ],
  done: [
    {
      title: '序号',
      dataIndex: 'no',
      key: 'no',
      align: 'left',
      width: 80
    },
    {
      title: '账号',
      dataIndex: 'userPhone',
      key: 'userPhone',
      align: 'left'
    },
    {
      title: '就诊人手机号',
      dataIndex: 'phone',
      key: 'phone',
      align: 'left'
    },
    {
      title: '就诊人',
      dataIndex: 'patName',
      key: 'patName',
      align: 'left'
    },
    {
      title: '证件号',
      dataIndex: 'idNo',
      key: 'idNo',
      align: 'left',
      width: 150
    },
    {
      title: '会员状态',
      dataIndex: 'memberState',
      key: 'memberState',
      align: 'left'
    },
    {
      title: '服务包有效期',
      dataIndex: 'buyTime',
      key: 'buyTime',
      align: 'left',
      width: 150
    },
    {
      title: '服务包名称',
      dataIndex: 'tradeName',
      key: 'tradeName',
      align: 'left'
    },
    {
      title: '管理路径',
      dataIndex: 'pathName',
      key: 'pathName',
      align: 'left'
    },
    {
      title: '问卷',
      dataIndex: 'managerName',
      key: 'managerName',
      align: 'left',
      width: 100
    },
    {
      title: '服务团队',
      dataIndex: 'groupName',
      key: 'groupName',
      align: 'left'
    },
    {
      title: '服务状态',
      dataIndex: 'serviceState',
      key: 'serviceState',
      align: 'left'
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      align: 'left',
      width: 100
    }
  ]
})
const pagination = ref<any>({
  current: 1,
  total: 0,
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100'],
  showQuickJumper: true
})
const paginationChange = (page: any) => {
  pagination.value = { ...page }
  loading.value = true
  getDataList()
}

const getDataList = () => {
  List.value = []
  const obj = condition.value.reduce((c, v) => {
    if (v.value || v.value === 0 || v.value === false) {
      if (v.dataIndex == 'visitTime') {
        return Object.assign(c, {
          visitTimeSta: v.value.length ? dayjs(v.value[0]).format('YYYY-MM-DD HH:mm:00') : '',
          visitTimeEnd: v.value.length ? dayjs(v.value[1]).format('YYYY-MM-DD HH:mm:00') : ''
        })
      } else if (v.dataIndex == 'buyTime') {
        return Object.assign(c, {
          buyTimeSta: v.value.length ? dayjs(v.value[0]).format('YYYY-MM-DD HH:mm:00') : '',
          buyTimeEnd: v.value.length ? dayjs(v.value[1]).format('YYYY-MM-DD HH:mm:00') : ''
        })
      } else {
        return Object.assign(c, { [v.dataIndex]: v.value })
      }
    } else {
      return c
    }
  }, {})
  getDispatchList({
    ...obj,
    page: pagination.value.current,
    limit: pagination.value.pageSize,
    serviceState:
      raidoValue.value == 'todo'
        ? obj.serviceState
          ? [obj.serviceState]
          : ['TODO', 'DOING']
        : ['DONE'],
    isSet: true,
    manager: store.userApp.userInfo.id,
    diseaseType: 'weightLose',
    chose: false
  })
    .then((res) => {
      dispatchAllCounts.value = res.data
      List.value = res.data.page.list
      pagination.value.total = res.data.page.total
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}
onMounted(() => {
  condition.value = conditioning.value
  if (route.query && route.query.type === 'manaPlan') {
    showDetail.value = true
    nextTick(() => {
      manaPlanRef.value.init(
        {
          ...route.query,
          empi: route.query.empi,
          userId: route.query.userId,
          back: route.query.back,
          backtype: route.query.backtype ? route.query.backtype : ''
        },
        'weightLose'
      )
    })
  }
  columns.value = columnsData.value[raidoValue.value]
  loading.value = true
  getDataList()
})

const manaPlanRef = ref()
const addOrUpdateHandle = (data) => {
  showDetail.value = true
  nextTick(() => {
    manaPlanRef.value.init(data, 'weightLose')
  })
}
const followInfoRef = ref()
const followInfo = (item) => {
  followInfoRef.value.init(item)
}
// 待办列表 多选
const rowSelection = computed(() => {
  if (raidoValue.value === 'todo') {
    return {
      selectedRowKeys: unref(selectedKeys),
      onChange: onSelectChange,
      getCheckboxProps: (record) => ({
        disabled: !record.questionState // 禁用
      })
    }
  } else {
    return null
  }
})

// 选择
const onSelectChange = (selectedRowKeys: Key[]) => {
  selectedKeys.value = selectedRowKeys
}

// 患者详情
const patientInfoRef = ref()
const toDetail = (data) => {
  showPatientInfo.value = true
  nextTick(() => {
    patientInfoRef.value.init(data)
  })
}

// 批量推送
const batchPush = () => {
  if (selectedKeys.value.length > 0) {
    isPushPlan.value = true
  } else {
    message.warning('请选择需要推送方案的患者')
  }
}

const raidoValueChange = (e) => {
  selectedKeys.value = []
  condition.value = []
  columns.value = columnsData.value[e.target.value]
  if (e.target.value == 'done') {
    condition.value = [...condition.value, ...conditionEd.value]
  } else {
    condition.value = [...condition.value, ...conditioning.value]
  }
  reset()
}

const searchHandle = () => {
  pagination.value.current = 1
  loading.value = true
  getDataList()
}
const reset = () => {
  pagination.value.current = 1
  pagination.value.pageSize = 10
  condition.value.map((v) => {
    if (v.type === 'select') {
      v.value = undefined
    } else if (v.type === 'dayRange') {
      v.value = []
    } else {
      v.value = ''
    }
  })
  selectedKeys.value = []
  loading.value = true
  getDataList()
}

const goBack = () => {
  router.replace({ query: {} })
  showDetail.value = false
  showPatientInfo.value = false
  loading.value = true
  getDataList()
}

const gopatientBack = () => {
  showDetail.value = false
  showPatientInfo.value = false
  loading.value = true
  getDataList()
}

// 确认推送
const pushPlanBtn = () => {
  const selectData = List.value.filter((v) => {
    if (selectedKeys.value.includes(v.id)) {
      return v
    }

    return false
  })
  isCreateHealthInfo.value = true
  batchPushScheme(selectData)
    .then((res) => {
      message.success('推送成功')
      isPushPlan.value = false
      selectedKeys.value = []
      loading.value = true
      getDataList()
    })
    .catch(() => {
      isCreateHealthInfo.value = false
    })
}
</script>
<style lang="less" scoped>
.header {
  display: flex;
  justify-content: space-between;
}

.main {
  flex: 1 1 auto;
  margin-top: 16px;
  overflow: hidden auto;

  .table {
    .questionName {
      color: #1677ff;

      &:hover {
        cursor: pointer;
        opacity: 0.8;
      }
    }
  }
}

.page-content {
  padding: 16px;
}
</style>
